//! Nacos服务器核心实现

use nacos_cluster::{ClusterManager, ClusterConfig, DataSyncManager, ConsistencyManager, ClusterConfigManager};
use nacos_naming::service::NamingServiceImpl;
use nacos_config::service::ConfigServiceImpl;
use nacos_network::service::NetworkServiceImpl;
use nacos_core::Result;
use nacos_storage::memory::{MemoryServiceStorage, MemoryConfigStorage};
use crate::api::ApiConfig;
use crate::api::server::ApiServer;
use crate::cluster_adapter::ClusterIntegrationManager;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, error};

/// 服务器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// 服务器端口
    pub port: u16,
    /// 服务器IP
    pub ip: String,
    /// 集群配置
    pub cluster: ClusterConfig,
    /// 命名服务配置
    pub naming: nacos_core::NamingConfig,
    /// 配置服务配置
    pub config: nacos_core::ConfigConfig,
    /// 网络配置
    pub network: nacos_core::NetworkConfig,
    /// 是否启用TLS
    pub tls_enabled: bool,
    /// 最大连接数
    pub max_connections: usize,
    /// 请求超时时间（毫秒）
    pub request_timeout: u64,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            port: 8848,
            ip: "0.0.0.0".to_string(),
            cluster: ClusterConfig::default(),
            naming: nacos_core::NamingConfig::default(),
            config: nacos_core::ConfigConfig::default(),
            network: nacos_core::NetworkConfig::default(),
            tls_enabled: false,
            max_connections: 1000,
            request_timeout: 5000,
        }
    }
}

/// 服务器状态
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ServerState {
    /// 初始化
    Initializing,
    /// 启动中
    Starting,
    /// 运行中
    Running,
    /// 停止中
    Stopping,
    /// 已停止
    Stopped,
    /// 错误
    Error,
}

/// 服务器统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerStats {
    /// 启动时间
    pub start_time: chrono::DateTime<chrono::Utc>,
    /// 当前状态
    pub state: ServerState,
    /// 总连接数
    pub total_connections: usize,
    /// 活跃连接数
    pub active_connections: usize,
    /// 总请求数
    pub total_requests: u64,
    /// 错误请求数
    pub error_requests: u64,
    /// 集群节点数
    pub cluster_nodes: usize,
    /// 健康节点数
    pub healthy_nodes: usize,
}


/// Nacos服务器
pub struct NacosServer {
    /// 服务器配置
    config: ServerConfig,
    /// 服务器状态
    state: Arc<RwLock<ServerState>>,
    /// 集群集成管理器
    cluster_integration: Arc<ClusterIntegrationManager>,
    /// 命名服务
    naming_service: Arc<NamingServiceImpl>,
    /// 配置服务
    config_service: Arc<ConfigServiceImpl>,
    /// 网络服务
    network_service: Arc<NetworkServiceImpl>,
    /// API服务器
    api_server: Arc<RwLock<Option<ApiServer>>>,
    /// 统计信息
    stats: Arc<RwLock<ServerStats>>,
}

impl NacosServer {
    /// 创建新的Nacos服务器
    pub fn new(config: ServerConfig) -> Result<Self> {
        info!("Creating new Nacos server with config: {:?}", config);

        let cluster_manager = Arc::new(ClusterManager::new(config.cluster.clone()));
        let data_sync_manager = Arc::new(DataSyncManager::new(cluster_manager.clone(), 3, 100));
        let consistency_manager = Arc::new(ConsistencyManager::new(
            data_sync_manager.clone(),
            cluster_manager.clone(),
            nacos_cluster::ConsistencyProtocol::Strong,
            5000,
        ));
        let config_manager = Arc::new(ClusterConfigManager::new(cluster_manager.clone(), data_sync_manager.clone()));

        let cluster_integration = Arc::new(ClusterIntegrationManager::new(
            cluster_manager,
            data_sync_manager,
            consistency_manager,
            config_manager,
        ));

        // 创建存储实例
        let service_storage = Arc::new(MemoryServiceStorage::new());
        let config_storage = Arc::new(MemoryConfigStorage::new());
        
        // 创建事件发布器实例
        let event_publisher = Arc::new(nacos_storage::memory::storage::MemoryStorage::new());
        
        // 创建服务实例
        let naming_service = Arc::new(NamingServiceImpl::new(
            service_storage,
            event_publisher.clone(),
            Arc::new(NetworkServiceImpl::new()),
        ));
        let config_service = Arc::new(ConfigServiceImpl::new(
            config_storage,
            event_publisher.clone(),
        ));
        let network_service = Arc::new(NetworkServiceImpl::new());

        let stats = Arc::new(RwLock::new(ServerStats {
            start_time: chrono::Utc::now(),
            state: ServerState::Initializing,
            total_connections: 0,
            active_connections: 0,
            total_requests: 0,
            error_requests: 0,
            cluster_nodes: 0,
            healthy_nodes: 0,
        }));

        Ok(Self {
            config,
            state: Arc::new(RwLock::new(ServerState::Initializing)),
            cluster_integration,
            naming_service,
            config_service,
            network_service,
            api_server: Arc::new(RwLock::new(None)),
            stats,
        })
    }

    /// 启动服务器
    pub async fn start(&self) -> Result<()> {
        info!("Starting Nacos server...");
        
        *self.state.write().await = ServerState::Starting;

        // 启动集群管理器
        self.start_cluster().await?;

        // 启动网络服务
        self.start_network_service().await?;

        // 启动命名服务
        self.start_naming_service().await?;

        // 启动配置服务
        self.start_config_service().await?;

        // 启动API服务器
        self.start_api_server().await?;

        // 启动监控服务
        self.start_monitoring().await?;

        *self.state.write().await = ServerState::Running;
        info!("Nacos server started successfully");

        Ok(())
    }

    /// 停止服务器
    pub async fn stop(&self) -> Result<()> {
        info!("Stopping Nacos server...");
        
        *self.state.write().await = ServerState::Stopping;

        // 停止API服务器
        if let Some(mut api_server) = self.api_server.write().await.take() {
            api_server.stop().await
                .map_err(|e| nacos_core::NacosError::Network(e.to_string()))?;
        }

        // 停止网络服务
        self.network_service.shutdown().await?;

        // 停止集群集成管理器
        self.cluster_integration.stop().await?;

        *self.state.write().await = ServerState::Stopped;
        info!("Nacos server stopped");

        Ok(())
    }

    /// 启动集群
    async fn start_cluster(&self) -> Result<()> {
        info!("Starting cluster...");

        // 启动集群集成管理器
        self.cluster_integration.start().await?;

        // 启动心跳检查
        let cluster_integration = self.cluster_integration.clone();
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
                
                let status = match cluster_integration.get_cluster_status().await {
                    Ok(status) => status,
                    Err(e) => {
                        error!("获取集群状态失败: {}", e);
                        continue;
                    }
                };

                info!("集群状态: {:?}", status);
            }
        });

        info!("Cluster started");
        Ok(())
    }

    /// 启动网络服务
    async fn start_network_service(&self) -> Result<()> {
        info!("Starting network service...");
        self.network_service.start().await?;
        info!("Network service started");
        Ok(())
    }

    /// 启动命名服务
    async fn start_naming_service(&self) -> Result<()> {
        info!("Starting naming service...");
        self.naming_service.start().await?;
        info!("Naming service started");
        Ok(())
    }

    /// 启动配置服务
    async fn start_config_service(&self) -> Result<()> {
        info!("Starting config service...");
        self.config_service.start().await?;
        info!("Configuration service started");
        Ok(())
    }

    /// 启动API服务器
    async fn start_api_server(&self) -> Result<()> {
        info!("Starting API server...");
        
        let api_config = ApiConfig {
            rest_port: self.config.port,
            grpc_port: 9090,
            cors_enabled: true,
            rate_limit_enabled: true,
            max_connections: self.config.max_connections,
            request_timeout: self.config.request_timeout,
        };

        let mut api_server = ApiServer::new(
            api_config,
            self.naming_service.clone(),
            self.config_service.clone(),
            self.cluster_integration.clone(),
            self.state.clone(),
        );

        api_server.start().await
            .map_err(|e| nacos_core::NacosError::Network(e.to_string()))?;

        *self.api_server.write().await = Some(api_server);

        info!("API server started");
        Ok(())
    }

    /// 启动监控服务
    async fn start_monitoring(&self) -> Result<()> {
        let stats = self.stats.clone();
        let cluster_integration = self.cluster_integration.clone();

        tokio::spawn(async move {
            loop {
                tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
                
                let mut stats = stats.write().await;
                match cluster_integration.get_cluster_status().await {
                    Ok(status) => {
                        stats.cluster_nodes = status.total_nodes;
                        stats.healthy_nodes = status.healthy_nodes;
                        info!("Server stats: {:?}", *stats);
                    }
                    Err(e) => {
                        error!("获取集群状态失败: {}", e);
                    }
                }
            }
        });

        Ok(())
    }

    /// 获取服务器状态
    pub async fn get_state(&self) -> ServerState {
        *self.state.read().await
    }

    /// 获取统计信息
    pub async fn get_stats(&self) -> ServerStats {
        self.stats.read().await.clone()
    }

    /// 获取集群集成管理器
    pub fn get_cluster_integration(&self) -> &Arc<ClusterIntegrationManager> {
        &self.cluster_integration
    }

    /// 获取集群服务
    pub fn cluster_service(&self) -> Arc<dyn nacos_network::ClusterService> {
        self.cluster_integration.cluster_service()
    }

    /// 获取数据同步服务
    pub fn data_sync_service(&self) -> Arc<dyn nacos_network::DataSyncService> {
        self.cluster_integration.data_sync_service()
    }

    /// 获取命名服务
    pub fn get_naming_service(&self) -> &Arc<NamingServiceImpl> {
        &self.naming_service
    }

    /// 获取配置服务
    pub fn get_config_service(&self) -> &Arc<ConfigServiceImpl> {
        &self.config_service
    }

    /// 健康检查
    pub async fn health_check(&self) -> Result<bool> {
        let state = self.get_state().await;
        Ok(matches!(state, ServerState::Running))
    }

    /// 获取服务器信息
    pub async fn get_server_info(&self) -> Result<ServerInfo> {
        let stats = self.get_stats().await;
        let state = self.get_state().await;

        Ok(ServerInfo {
            ip: self.config.ip.clone(),
            port: self.config.port,
            state,
            start_time: stats.start_time,
            version: env!("CARGO_PKG_VERSION").to_string(),
            cluster_nodes: stats.cluster_nodes,
            healthy_nodes: stats.healthy_nodes,
        })
    }
}

/// 服务器信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerInfo {
    /// 服务器IP
    pub ip: String,
    /// 服务器端口
    pub port: u16,
    /// 当前状态
    pub state: ServerState,
    /// 启动时间
    pub start_time: chrono::DateTime<chrono::Utc>,
    /// 版本号
    pub version: String,
    /// 集群节点数
    pub cluster_nodes: usize,
    /// 健康节点数
    pub healthy_nodes: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_server_creation() {
        let config = ServerConfig::default();
        let server = NacosServer::new(config).unwrap();
        
        assert_eq!(server.config.port, 8848);
        assert!(matches!(server.get_state().await, ServerState::Initializing));
    }

    #[tokio::test]
    async fn test_server_start_stop() {
        let config = ServerConfig::default();
        let server = NacosServer::new(config).unwrap();
        
        // 启动服务器
        server.start().await.unwrap();
        assert!(matches!(server.get_state().await, ServerState::Running));
        
        // 停止服务器
        server.stop().await.unwrap();
        assert!(matches!(server.get_state().await, ServerState::Stopped));
    }

    #[tokio::test]
    async fn test_server_info() {
        let config = ServerConfig::default();
        let server = NacosServer::new(config).unwrap();
        
        server.start().await.unwrap();
        
        let info = server.get_server_info().await.unwrap();
        assert_eq!(info.port, 8848);
        assert_eq!(info.ip, "0.0.0.0");
        assert!(!info.version.is_empty());
    }
}